package com.xiaoke.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoke.domain.ResponseResult;
import com.xiaoke.domain.dto.LoginDto;
import com.xiaoke.domain.entity.Comment;
import com.xiaoke.domain.entity.LoginUser;
import com.xiaoke.domain.entity.User;
import com.xiaoke.domain.vo.LoginVo;
import com.xiaoke.mapper.CommentMapper;
import com.xiaoke.mapper.UserMapper;
import com.xiaoke.service.LoginService;
import com.xiaoke.utils.BeanCopyUtils;
import com.xiaoke.utils.JwtUtil;
import com.xiaoke.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


/**
 * 登录服务实现类
 *
 * @author xiaoke
 * @since 2023-03-22 17:44:56
 */

@Service("loginService")
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {


    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisCache redisCache;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginDto.getUserName(),loginDto.getPassword());
//
        Authentication authenticate =  authenticationManager.authenticate(authentication);
        //校验失败了
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("账号或密码错误！");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        User user = loginUser.getUser();
        String userID = user.getId().toString();
        String jwt = JwtUtil.createJWT(userID);
        user.setToken(jwt);

        LoginVo loginVo = BeanCopyUtils.copyBean(user, LoginVo.class);

        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        redisCache.setCacheObject("login:" + userID, loginUser);

        return ResponseResult.okResult(loginVo);
    }
}
